package com.playball.lottery.frm.yhzx;

import android.app.Activity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.ApplicationData;
import com.playball.lottery.R;
import com.playball.lottery.util.ConvertJsonToList;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TCaiRechargeActivity extends Activity implements View.OnClickListener {
    public static String OUT_TRADE_NO="123456789";
    public static final String APP_ID="wxdc60f7a9db5224ea";
    private  TextView top_title_back,top_title_info,text_recharge_name,txet_recharge_money;
    private  RadioGroup redio_group_wx1;
    private RadioButton radio_btn_wx1,radio_btn_wx2,radio_btn_wx3,radio_btn_wx4,radio_btn_wx5,radio_btn_wx6,radio_btn_wx7,radio_btn_wx8;
    private EditText edit_recharge_wx;
    private Button btn_recharge_wx;
    private String recharge_money;
    private IWXAPI api;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tcai_recharge);
        api= WXAPIFactory.createWXAPI(this,APP_ID);
        api.registerApp(APP_ID);
        initView();
        top_title_info.setText("微信支付充值");
        text_recharge_name.setText(ApplicationData.getInstance().getUserName());
        txet_recharge_money.setText(ApplicationData.getInstance().getUserMoney());
    }

    private void initView() {
        top_title_back= (TextView) findViewById(R.id.top_title_wx_back);
        top_title_info= (TextView) findViewById(R.id.top_title_wx_info);
        text_recharge_name= (TextView) findViewById(R.id.text_recharge_name);
        txet_recharge_money= (TextView) findViewById(R.id.txet_recharge_money);
        redio_group_wx1= (RadioGroup) findViewById(R.id.redio_group_wx1);
        radio_btn_wx1= (RadioButton) findViewById(R.id.radio_btn_wx1);
        radio_btn_wx2= (RadioButton) findViewById(R.id.radio_btn_wx2);
        radio_btn_wx3= (RadioButton) findViewById(R.id.radio_btn_wx3);
        radio_btn_wx4= (RadioButton) findViewById(R.id.radio_btn_wx4);
        radio_btn_wx5= (RadioButton) findViewById(R.id.radio_btn_wx5);
        radio_btn_wx6= (RadioButton) findViewById(R.id.radio_btn_wx6);
        radio_btn_wx7= (RadioButton) findViewById(R.id.radio_btn_wx7);
        radio_btn_wx8= (RadioButton) findViewById(R.id.radio_btn_wx8);
        edit_recharge_wx= (EditText) findViewById(R.id.edit_recharge_wx);
        btn_recharge_wx= (Button) findViewById(R.id.btn_recharge_wx);
        redio_group_wx1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                radiogroupchecked(checkedId);
            }
        });
        top_title_back.setOnClickListener(this);
        btn_recharge_wx.setOnClickListener(this);
    }
    private void radiogroupchecked(int checkedId) {
        switch (checkedId){
            case R.id.radio_btn_wx1:
                recharge_money="10";
                edit_recharge_wx.setVisibility(View.INVISIBLE);
                break;
            case R.id.radio_btn_wx2:
                recharge_money="50";
                edit_recharge_wx.setVisibility(View.INVISIBLE);
                break;
            case R.id.radio_btn_wx3:
                recharge_money="100";
                edit_recharge_wx.setVisibility(View.INVISIBLE);
                break;
            case R.id.radio_btn_wx4:
                recharge_money="200";
                edit_recharge_wx.setVisibility(View.INVISIBLE);
                break;
            case R.id.radio_btn_wx5:
                recharge_money="500";
                edit_recharge_wx.setVisibility(View.INVISIBLE);
                break;
            case R.id.radio_btn_wx6:
                recharge_money="1000";
                edit_recharge_wx.setVisibility(View.INVISIBLE);
                break;
            case R.id.radio_btn_wx7:
                recharge_money="5000";
                edit_recharge_wx.setVisibility(View.INVISIBLE);
                break;
            case R.id.radio_btn_wx8:
                edit_recharge_wx.setVisibility(View.VISIBLE);
                break;
        }
    }
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_title_wx_back:
                finish();
                break;
            case R.id.btn_recharge_wx:
                if (recharge_money==null||"".equals(recharge_money)){
                    String money=edit_recharge_wx.getText().toString();
                    if (money==null||"".equals(money)){
                        Toast.makeText(this,"请输入金额",Toast.LENGTH_SHORT).show();
                    }else {
                        recharge_money=edit_recharge_wx.getText().toString();
                    }
                }
                if(isWeixinAvilible(this)){
                    if (api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT){
                        dopost();
                    }else {
                        Toast.makeText(this,"微信版本不支持支付",Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(this,"请先安装微信",Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }

    private void dopost() {
        String url= "http://weixin.tcaio2o.com/Recharge/AppCharge?body=asd&total_fee="+recharge_money+"&UserID="+ApplicationData.getInstance().getUserID();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                android.util.Log.e("=========1======",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str=response.body().string();
                if(response.isSuccessful()){
                    android.util.Log.e("========2=======",str);
                    try{
                        JSONTokener jsonParser = new JSONTokener(str);
                        JSONObject js = (JSONObject) jsonParser.nextValue();
                        if (js.getInt("Code") == 0) {
                            Map<String, Object> map = ConvertJsonToList.getMap(js.getString("Data"));
                            String prepayId=map.get("prepay_id").toString();
                            String nonceStr=map.get("nonceStr").toString();
                            String sign=map.get("sign").toString();
                            OUT_TRADE_NO=map.get("out_trade_no").toString();
                            String timeStamp=map.get("timestamp").toString();
                            PayReq req = new PayReq();
                            //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                            req.appId			= APP_ID;
                            req.partnerId		= "1468677802";
                            req.prepayId		= prepayId;
                            req.nonceStr		= nonceStr;
                            req.timeStamp		= timeStamp;
                            req.packageValue	= "Sign=WXPay";
                            req.sign			= sign;
                            req.extData			= "app data"; // optional
                            android.util.Log.e("=======3========","运行到了这里");
                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                            finish();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else {
                    android.util.Log.e("=======3========",str);
                }
            }
        });

    }


    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
    }
    /**
     * 检查微信是否存在
     * @param context
     * @return
     */
    public  boolean isWeixinAvilible(Context context) {
        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                System.out.println(pinfo.get(i).packageName);
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
}
